package com.wolfalpha.utron.service.impl;

import com.wolfalpha.utron.app.AppConfig;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.bean.InitRequirement;
import com.wolfalpha.utron.bean.ItemRequirement;
import com.wolfalpha.utron.net.URLs;
import com.wolfalpha.utron.service.ReuirementService;
import com.wolfalpha.utron.utils.JsonUtils;


import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by luodon on 15/8/20.
 */
public class RequirementServiceImpl implements ReuirementService {


    @Override
    public List<ItemRequirement> getList(int page) {
        List<ItemRequirement> requirements = new ArrayList<ItemRequirement>();
        Map<String, String> mp = new HashMap<>();
        mp.put("user_id", AppContext.getInstance().getUserId() + "");
        mp.put("page", String.valueOf(page));
        String result = AppContext.getApiClient().sendPostResquest(URLs.REQUIRE_GET_LIST, mp);
        if (result == null) {
            return null;
        }
        System.out.println(result.toString());
        try {
            JSONArray arr = new JSONArray(JsonUtils.getData(result));
            for (int i = 0; i < arr.length(); i++) {
                ItemRequirement itemRequirement = JsonUtils.paraseJson(arr.get(i).toString(), ItemRequirement.class);
                requirements.add(itemRequirement);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return requirements;
    }

    @Override
    public InitRequirement getOne() {
        String result = AppContext.getApiClient().sendGetResquest(URLs.REQUIRE_GET_ONE);
        if (result != null) {
            System.out.println(result.toString());
//            System.out.println(JsonUtils.getData(result));
        }
        return result == null ? null : JsonUtils.paraseJson(JsonUtils.getData(result), InitRequirement.class);
    }

    @Override
    public boolean publishOne(String content) {
        Map<String, String> mp = new HashMap<>();
        mp.put("user_id", AppContext.getInstance().getUserId() + "");
        mp.put("content", content);
        String result = AppContext.getApiClient().sendPostResquest(URLs.REQUIRE_PUBLISH_ONE, mp);
        return result == null ? false : JsonUtils.getRet(result) == 200;
    }

    @Override
    public boolean doForOne(boolean yes, int rid) {
        Map<String, String> mp = new HashMap<>();
        mp.put("requirement_id", String.valueOf(rid));
        mp.put("do", yes ? "yes" : "no");
        String result = AppContext.getApiClient().sendPostResquest(URLs.REQUIRE_URL + "do", mp);
        return result == null ? false : JsonUtils.getRet(result) == 200;
    }
}
